//
//  CustomPhotoDisplayScrollView.m
//  照片展示
//
//  Created by MyMac on 15/7/9.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "CustomPhotoDisplayScrollView.h"
@interface CustomPhotoDisplayScrollView()<UIScrollViewDelegate>

@end
@implementation CustomPhotoDisplayScrollView
-(instancetype)initWithFrame:(CGRect)frame
{
    if([super initWithFrame:frame]){
        self.imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 100, frame.size.width, frame.size.height-200)];
        self.backgroundColor=[UIColor redColor];
        self.imageView.userInteractionEnabled=YES;
        self.imageView.contentMode=UIViewContentModeScaleAspectFill;
        self.delegate=self;
        [self addSubview:self.imageView];
        [self.imageView addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
       
    
    
    
    
    }


    return self;

}
- (void)drawRect:(CGRect)rect {
    
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
   UIImage*image=change[NSKeyValueChangeNewKey];
    self.imageView.bounds=CGRectMake(0, 0,image.size.width, image.size.height);
    CGSize maxSize = self.frame.size;
    CGFloat widthRatio = maxSize.width/image.size.width;
    CGFloat heightRatio = maxSize.height/image.size.height;
    CGFloat initialZoom = (widthRatio > heightRatio) ? heightRatio : widthRatio;
    
    [self setMinimumZoomScale:initialZoom];
    [self setMaximumZoomScale:5];
    // 设置UIScrollView初始化缩放级别
    [self setZoomScale:initialZoom];
    

}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;
{
    return self.imageView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{

    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    self.imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                         scrollView.contentSize.height * 0.5 + offsetY);

}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    
    [scrollView setZoomScale:scale animated:YES];
    NSLog(@"%lf",scale);

    
}

@end
